<template>
  <div id="mapContainer">
    <div class="panel">
      <el-button @click="handleDrawRadiationCircle">绘制流动线</el-button>
    </div>
  </div>
</template>
<script setup>
import { Map, View } from "ol";
import { fromLonLat, get } from "ol/proj";

import { Tile as TileLayer, Vector as VectorLayer } from "ol/layer";
import { Vector as VectorSource } from "ol/source";
import Feature from "ol/feature";
import { Point, LineString, Polygon, Circle } from "ol/geom";
import {
  Style,
  Stroke,
  Fill,
  Circle as CircleStyle,
  Icon,
  Text,
} from "ol/style";

import GeoJSON from "ol/format/GeoJSON.js";

import * as turf from "@turf/turf";
import * as radash from "radash";

import { onMounted, nextTick, ref } from "vue";

import { tdt_api_key /** 天地图的key */ } from "@/config/keys.json";
import { addTdtBaseLayer } from "@/utils/baseMap.js";

import { getLayerByName } from "@/utils/layer.js";

import { flyTo, flyToFeature, getExtent } from "../../utils/view";
import { randomLineStringFeature } from "../../utils/random";
import { drawRadiationCircle } from "../../utils/draw";

function initMap() {
  const map = new Map({
    view: new View({
      //   center: fromLonLat([114.5, 31]),
      projection: "EPSG:4326",
      center: [114.5, 31],
      zoom: 9,
    }),
    target: "mapContainer",
    controls: [],
  });

  // 加载底图
  addTdtBaseLayer(map, tdt_api_key, "img", "c", "wmts");
  window.map = map;
}

onMounted(() => {
  nextTick(() => {
    initMap();
  });
});

function handleDrawRadiationCircle() {
  // 流动线图层
  const layer = new VectorLayer({
    properties: {
      name: "流动线",
      type: "flowLine",
    },
    source: new VectorSource({
      features: [],
    }),
  });

  window.map.addLayer(layer);

  const lineString = randomLineStringFeature(window.map, 1)[0];
  layer.getSource().addFeature(lineString);

  flyToFeature(window.map, lineString);

  let lineDashOffset = 0;

  // 获取流动线样式
  const getFlowLineStyle = lineDashOffset => {
    return [
      new Style({
        stroke: new Stroke({
          color: "#5298FF",
          width: 12,
        }),
      }),
      new Style({
        stroke: new Stroke({
          color: "#fff",
          width: 3,
          lineDash: [10, 10],
          lineDashOffset,
        }),
      }),
    ];
  };

  //给图层添加样式
  layer.setStyle(getFlowLineStyle(lineDashOffset));

  // 流动线动画
  const flowLineAnimation = () => {
    lineDashOffset = lineDashOffset <= -10 ? 0 : lineDashOffset - 0.3;

    if (layer) {
      layer.setStyle(getFlowLineStyle(lineDashOffset));
      requestAnimationFrame(flowLineAnimation);
    }
  };

  flowLineAnimation();
}
</script>

<style scoped>
#mapContainer {
  width: 100%;
  height: 99vh;
}

.panel {
  position: absolute;
  top: 10px;
  left: 150px;
  z-index: 999;
}
</style>
